<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="25%" :title="`${drawerProps.title}-用户管理`">
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=":" :rules="rules" :model="operateDataInfo">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="operateDataInfo.nickName" placeholder="请输入用户昵称" clearable></el-input>
      </el-form-item>
      <el-space v-if="drawerProps.isSave" fill>
        <el-alert type="info" show-icon :closable="false">
          <p>用户名与初始登录密码用于登录,用户名无法修改!</p>
        </el-alert>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="operateDataInfo.userName" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="初始密码" prop="password">
          <el-input
            v-model="operateDataInfo.password"
            type="password"
            show-password
            placeholder="请输入初始密码"
            clearable
          ></el-input>
        </el-form-item>
      </el-space>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="operateDataInfo.email" placeholder="请输入电子邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="移动电话" prop="mobile">
        <el-input v-model="operateDataInfo.mobile" placeholder="请输入移动电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户状态" prop="userStatus">
        <el-select v-model="operateDataInfo.userStatus" placeholder="请选择用户状态">
          <el-option
            v-for="item in drawerProps.enumMap?.get('userStatus')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="operateDataInfo.deptId"
          style="width: 100%"
          value-key="id"
          :data="drawerProps.enumMap?.get('deptInfo.id')"
          :props="{ label: data => data.deptName }"
          :render-after-expand="false"
          highlight-current
          check-strictly
          check-on-click-node
          placeholder="请选择所属部门"
        />
      </el-form-item>
      <el-form-item label="用户角色" prop="roleIdList">
        <el-select v-model="operateDataInfo.roleIdList" multiple placeholder="请选择用户角色">
          <el-option
            v-for="item in drawerProps.enumMap?.get('roleIdList')"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getUserInfo, SysUserInfoResult, SysUserSaveParam, SysUserUpdateParam } from "@/api/modules/sys/user";

interface DrawerProps {
  title: string;
  isSave: boolean;
  isUpdate: boolean;
  row: Partial<SysUserInfoResult>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  enumMap?: Map<string, { [key: string]: any }[]>;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  title: "",
  isSave: false,
  isUpdate: false,
  row: {}
});

const rules = reactive({
  nickName: [{ required: true, message: "请填写用户昵称" }],
  userName: [{ required: true, message: "请填写用户名", pattern: /^[a-zA-Z0-9_]*$/ }],
  password: [{ required: true, message: "请填写初始登录密码" }],
  userStatus: [{ required: true, message: "请选择用户状态" }],
  deptId: [{ required: true, message: "请选择用户所属部门" }],
  roleIdList: [{ required: true, message: "请选择用户角色" }]
});

const operateDataInfo = ref<SysUserSaveParam | SysUserUpdateParam>({});
const openDrawer = async (params: DrawerProps) => {
  if (params.isUpdate) {
    // 更新信息，先查询
    let { data } = await getUserInfo(params.row.id ? params.row.id : "");
    operateDataInfo.value = { ...data, deptId: data.deptInfo.id, roleIdList: data.roleInfoList.map(role => role.id) };
  } else if (params.isSave) {
    // 新增前的默认值
    operateDataInfo.value = { userStatus: 1 };
  }
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(operateDataInfo.value);
      ElMessage.success({ message: `${drawerProps.value.title} 成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  openDrawer
});
</script>

<style scoped lang="scss"></style>
